<?php

namespace app\mall\controller\admin;


use suframe\thinkAdmin\traits\CURDController;
use suframe\thinkAdmin\ui\UITable;
use app\mall\model\MallGoods as MallGoodsModel;
use think\Exception;

/**
 * 公共商品
 */
class MallGoods extends Base
{
    use CURDController;
    protected $urlPre = '/mall/admin/mallGoods/';

    private function getManageModel()
    {
        return MallGoodsModel::class;
    }

    private function ajaxSearch()
    {
        /** @var MallGoodsModel $model */
        $model = $this->getManageModel();
        $model = $model::where(1, 1);
        if ($search_cate_ids = $this->request->get('search_cate_ids')) {
            $model->where('cate_ids', 'like', '[' . implode(',', $search_cate_ids) . '%');
        }
        $rs = $this->parseSearchWhere($model, [
            'title' => 'like',
        ])->append(['cate_name', 'freight_type_text', 'status_text', 'create_date']);

        //cate解析
        return json_return($rs);
    }

    /**
     * @param \suframe\form\Form $form
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \ReflectionException
     */
    private function getFormSetting($form)
    {
        $form->setRuleByClass(\app\mall\ui\form\MallGoodsForm::class);
    }

    /**
     * @param UITable $table
     */
    private function getTableSetting($table)
    {
        $table->createByClass(\app\mall\ui\table\MallGoodsTable::class);
        $table->setButtons('add', ['title' => '增加', 'url' => $this->urlABuild('update')]);
        $table->setEditOps($this->urlA('update'), ['id']);
        $table->setDeleteOps($this->urlA('delete'), ['id']);
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getUpdateInfo()
    {
        if ($id = $this->request->param('id')) {
            /** @var \app\mall\model\MallGoods $model */
            $model = $this->getManageModel()::with(['detail']);
            $rs = $model->find($id);
            return $rs;
        }
        return [];
    }

    /**
     * @param \app\mall\model\MallGoods $info
     * @param $post
     * @return mixed
     */
    private function beforeSave($info, $post)
    {
        if (isset($post['cate_id']) && is_array($post['cate_id'])) {
            $post['cate_id'] = array_pop($post['cate_id']);
        }
        //关联更新
        $info->updateRelation(['detail'], $post);
        return $post;
    }

    /**
     * @param MallGoodsModel $model
     * @throws Exception
     */
    private function beforeDelete($model)
    {
        if (!$this->getAdminUser()->isSupper()) {
            throw new Exception("请用超级管理员账户删除");
        }
        if ($model->statusEnum->valid()) {
            throw new Exception("商品上加中，不允许删除");
        }
    }
}